package com.castle.fortress.admin.study.course.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.study.course.dto.StudyCourseChapterDto;
import com.castle.fortress.admin.study.course.dto.StudyCourseLogDto;
import com.castle.fortress.admin.study.course.dto.StudyCoursewareDto;
import com.castle.fortress.admin.study.course.entity.StudyCourseChapterCoursewareEntity;
import com.castle.fortress.admin.study.course.entity.StudyCourseChapterEntity;
import com.castle.fortress.admin.study.course.entity.StudyCourseLogEntity;
import com.castle.fortress.admin.study.course.service.StudyCourseChapterCoursewareService;
import com.castle.fortress.admin.study.course.service.StudyCourseChapterService;
import com.castle.fortress.admin.study.course.service.StudyCourseLogService;
import com.castle.fortress.admin.study.course.service.StudyCourseService;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.CourseStatusEnum;
import com.castle.fortress.common.enums.CourseStudyStatusEnum;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 课程章节表 控制器
 *
 * @author castle
 * @since 2023-01-31
 */
@Api(tags="课程章节表管理控制器")
@Controller
public class StudyCourseChapterController {
    @Autowired
    private StudyCourseChapterService studyCourseChapterService;
    @Autowired
    private StudyCourseChapterCoursewareService studyCourseChapterCoursewareService;
    @Autowired
    private StudyCourseLogService studyCourseLogService;
    @Autowired
    private StudyCourseService studyCourseService;

    /**
     * 课程章节表的分页展示
     * @param studyCourseChapterDto 课程章节表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程章节表分页展示")
    @GetMapping("/study/course/studyCourseChapter/page")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseChapter:pageList")
    public RespBody<IPage<StudyCourseChapterDto>> pageStudyCourseChapter(StudyCourseChapterDto studyCourseChapterDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<StudyCourseChapterDto> page = new Page(pageIndex, pageSize);
        IPage<StudyCourseChapterDto> pages = studyCourseChapterService.pageStudyCourseChapterExtends(page, studyCourseChapterDto);

        return RespBody.data(pages);
    }

    /**
     * 课程章节表的列表展示
     * @param studyCourseChapterDto 课程章节表实体类
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程章节表列表展示")
    @GetMapping("/study/course/studyCourseChapter/list")
    @ResponseBody
    public RespBody<List<StudyCourseChapterDto>> listStudyCourseChapter(StudyCourseChapterDto studyCourseChapterDto){
        List<StudyCourseChapterDto> list = studyCourseChapterService.listStudyCourseChapter(studyCourseChapterDto);
        return RespBody.data(list);
    }

    /**
     * 课程章节表保存
     * @param chapterDTOS 课程章节表实体类列表
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.INSERT)
    @ApiOperation("课程章节表保存")
    @PostMapping("/study/course/studyCourseChapter/save")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseChapter:save")
    @Transactional(rollbackFor = Exception.class)
    public RespBody<String> saveStudyCourseChapter(@RequestBody List<StudyCourseChapterDto> chapterDTOS){
        System.err.println(chapterDTOS);
        //先根据课程ID 删除之前所有的章节及课件....
        if (chapterDTOS.size()>0){
            Long courseId = chapterDTOS.get(0).getCourseId();
            Integer courseStatus = chapterDTOS.get(0).getCourseStatus();
            Integer isRecommend = chapterDTOS.get(0).getIsRecommend();
            if(!CourseStatusEnum.PUTAWAY.getCode().equals(courseStatus)){
                isRecommend = YesNoEnum.NO.getCode();
            }
            studyCourseService.updateAllStatus(courseId,courseStatus,isRecommend);
            //删掉本课程下所有的章节以及课件/重新写入新的
            studyCourseChapterService.delByCourseId(courseId);
            studyCourseChapterCoursewareService.delByCourseId(courseId);
            System.err.println(chapterDTOS);

            // 查所有用户的学习记录  删掉删掉的章节课件 增加新增的章节课件
            StudyCourseLogDto studyCourseLogDto = new StudyCourseLogDto();
            studyCourseLogDto.setCourseId(courseId);
            List<StudyCourseLogDto> courseList = studyCourseLogService.listStudyCourseLog(studyCourseLogDto);
            studyCourseLogService.removeByCourseId(courseId);
            Map<String , List<StudyCourseLogDto>> chapterGroupMap = new HashMap<>();// 按章节的分组
            Map<String , List<StudyCourseLogDto>> chapterCoursewareGroupMap = new HashMap<>();// 按章节和课程的分组
            Set<Long> memberIdSet = new HashSet();// 正在学习此课程的会员id
            for (StudyCourseLogDto dto : courseList){
                memberIdSet.add(dto.getMemberId());
                List<StudyCourseLogDto> chapterGroupList = chapterGroupMap.get("" + dto.getChapterId());
                if (chapterGroupList != null){
                    chapterGroupList.add(dto);
                    chapterGroupMap.put("" + dto.getChapterId() , chapterGroupList);
                }else {
                    List<StudyCourseLogDto> list = new ArrayList<>();
                    list.add(dto);
                    chapterGroupMap.put("" + dto.getChapterId() , list);
                }
                List<StudyCourseLogDto> chapterCoursewareGroupList = chapterCoursewareGroupMap.get("" + dto.getChapterId() + dto.getCoursewareId());
                if (chapterCoursewareGroupList != null){
                    chapterCoursewareGroupList.add(dto);
                    chapterCoursewareGroupMap.put("" + dto.getChapterId() + dto.getCoursewareId() , chapterCoursewareGroupList);
                }else {
                    List<StudyCourseLogDto> list = new ArrayList<>();
                    list.add(dto);
                    chapterCoursewareGroupMap.put("" + dto.getChapterId() + dto.getCoursewareId() , list);
                }

            }
            List<StudyCourseLogDto> saveList = new ArrayList<>();
            for (int i=0;i<chapterDTOS.size();i++){
                StudyCourseChapterDto item = chapterDTOS.get(i);
                item.setSort(i);
                StudyCourseChapterEntity itemEntity= ConvertUtil.transformObj(item,StudyCourseChapterEntity.class);
                //先保存章节
                studyCourseChapterService.save(itemEntity);
                item.setId(itemEntity.getId());
                Collection<StudyCourseChapterCoursewareEntity> list = new ArrayList<>();
                //如果包含课件 保存课件
                System.err.println("===========item"+item);
                if (item.getCoursewares()!=null){
                    for(int j=0;j<item.getCoursewares().size();j++){
                        StudyCoursewareDto coursewareDTO = item.getCoursewares().get(j);
                        StudyCourseChapterCoursewareEntity children = new StudyCourseChapterCoursewareEntity();
                        //所属章节ID
                        children.setChapterId(item.getId());
                        //所属课程ID
                        children.setCourseId(item.getCourseId());
                        //所属课件ID
                        children.setCoursewareId(coursewareDTO.getId());
                        children.setSort(j);
                        list.add(children);
                    }
                }
                studyCourseChapterCoursewareService.saveBatch(list);
                Date now = new Date();
                // 判断章节原来存不存在 存在就再判断课件 不存在就给所有正在学此课的会员新增一条
                List<StudyCourseLogDto> logList = chapterGroupMap.get("" + item.getId());
                if (logList != null && logList.size() > 0){
                    // 判断课件原来存不存在 存在就直接保存 不存在就给所有正在学此课的会员新增一条
                    List<StudyCoursewareDto> coursewareList = item.getCoursewares();
                    for (StudyCoursewareDto coursewareDto : coursewareList){
                        List<StudyCourseLogDto> coursewareGroupList = chapterCoursewareGroupMap.get("" + item.getId() + coursewareDto.getId());
                        if (coursewareGroupList != null && coursewareGroupList.size() > 0){
                            saveList.addAll(coursewareGroupList);
                        }else {
                            for (Long memberId : memberIdSet){
                                StudyCourseLogDto logDto = new StudyCourseLogDto();
                                logDto.setCourseId(courseId);
                                logDto.setChapterId(item.getId());
                                logDto.setCoursewareId(coursewareDto.getId());
                                logDto.setMemberId(memberId);
                                logDto.setStatus(CourseStudyStatusEnum.NO_START.getCode());
                                logDto.setStudyTime(0);
                                logDto.setCreateTime(now);
                                saveList.add(logDto);
                            }
                        }

                    }
                }else {
                    if (memberIdSet.size() > 0 && item.getCoursewares().size() > 0){
                        List<StudyCoursewareDto> coursewareList = item.getCoursewares();
                        for (StudyCoursewareDto coursewareDto: coursewareList){
                            for (Long memberId : memberIdSet){
                                StudyCourseLogDto logDto = new StudyCourseLogDto();
                                logDto.setCourseId(courseId);
                                logDto.setChapterId(item.getId());
                                logDto.setCoursewareId(coursewareDto.getId());
                                logDto.setMemberId(memberId);
                                logDto.setStatus(CourseStudyStatusEnum.NO_START.getCode());
                                logDto.setStudyTime(0);
                                logDto.setCreateTime(now);
                                saveList.add(logDto);
                            }
                        }

                    }

                }
            }
            if (saveList.size() > 0){
                studyCourseLogService.saveBatch(ConvertUtil.transformObjList(saveList , StudyCourseLogEntity.class));
            }
        }else{
            throw new BizException(BizErrorCode.CHAPTERS_BE_EMPTY);
        }
        return RespBody.data("保存成功");
    }


    /**
     * 课程章节表编辑
     * @param studyCourseChapterDto 课程章节表实体类
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("课程章节表编辑")
    @PostMapping("/study/course/studyCourseChapter/edit")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseChapter:edit")
    public RespBody<String> updateStudyCourseChapter(@RequestBody StudyCourseChapterDto studyCourseChapterDto){
        if(studyCourseChapterDto == null || studyCourseChapterDto.getId() == null || studyCourseChapterDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCourseChapterEntity studyCourseChapterEntity = ConvertUtil.transformObj(studyCourseChapterDto,StudyCourseChapterEntity.class);
        if(studyCourseChapterService.updateById(studyCourseChapterEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程章节表删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("课程章节表删除")
    @PostMapping("/study/course/studyCourseChapter/delete")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseChapter:delete")
    public RespBody<String> deleteStudyCourseChapter(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(studyCourseChapterService.removeById(id)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 课程章节表批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("课程章节表批量删除")
    @PostMapping("/study/course/studyCourseChapter/deleteBatch")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseChapter:deleteBatch")
    public RespBody<String> deleteStudyCourseChapterBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(studyCourseChapterService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程章节表详情
     * @param id 课程章节表id
     * @return
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程章节表详情")
    @GetMapping("/study/course/studyCourseChapter/info")
    @ResponseBody
    @RequiresPermissions("study:course:studyCourseChapter:info")
    public RespBody<StudyCourseChapterDto> infoStudyCourseChapter(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCourseChapterDto studyCourseChapterDto =  studyCourseChapterService.getByIdExtends(id);

        return RespBody.data(studyCourseChapterDto);
    }

    //根据课程ID获取对应章节以及课件信息
    @GetMapping("/study/course/studyCourseChapter/detail/{id}")
    @ApiOperation("获取章节及课件信息")
    @ResponseBody
    public RespBody<List<StudyCourseChapterDto>> getDetail(@PathVariable("id") Long id){
        //根据课程ID获取对应的章节以及所属课件
//        cpbCourseChapterService.deleteByCourseId(courseId);
//        cpbCourseChapterCoursewareService.deleteByCourseId(courseId);
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        return RespBody.data(studyCourseChapterService.getListByCourseId(id));
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="课程章节表",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/study/course/studyCourseChapter/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<StudyCourseChapterDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<StudyCourseChapterDto> list = studyCourseChapterService.listStudyCourseChapter(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}




}
